package com.luck.easyfoodbatch.ui;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.Constant;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.OrderDetailsShopAdapter;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.OrderM;
import com.luck.easyfoodbatch.mvp.mine.UpdateMemberPresenter;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.MyOrdersM;
import com.luck.easyfoodbatch.mvp.model.OrderDetailM;
import com.luck.easyfoodbatch.mvp.order.CancelOrderModel;
import com.luck.easyfoodbatch.mvp.order.CancelOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.CancelOrderView;
import com.luck.easyfoodbatch.mvp.order.ConfirmOrderModel;
import com.luck.easyfoodbatch.mvp.order.ConfirmOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.ConfirmOrderView;
import com.luck.easyfoodbatch.mvp.order.DeleteOrderModel;
import com.luck.easyfoodbatch.mvp.order.DeleteOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.DeleteOrderView;
import com.luck.easyfoodbatch.mvp.order.OrderDetailModel;
import com.luck.easyfoodbatch.mvp.order.OrderDetailPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderDetailView;
import com.luck.easyfoodbatch.mvp.order.OrderPayModel;
import com.luck.easyfoodbatch.mvp.order.OrderPayPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderPayView;
import com.luck.easyfoodbatch.mvp.order.OrderRefundAllModel;
import com.luck.easyfoodbatch.mvp.order.OrderRefundAllPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderRefundAllView;
import com.luck.easyfoodbatch.pay.PayResult;
import com.luck.easyfoodbatch.simcpux.Constants;
import com.luck.easyfoodbatch.util.AlipayUtil;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.luck.easyrecyclerview.swipe.MyLayoutManager;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailsActivity extends BaseActivity implements OrderRefundAllView, OrderDetailView, OrderPayView, DeleteOrderView, CancelOrderView, ConfirmOrderView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_status)
    TextView tv_status;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_note)
    TextView tv_note;
    @BindView(R.id.tv_order_num)
    TextView tv_order_num;
    @BindView(R.id.tv_order_time)
    TextView tv_order_time;
    @BindView(R.id.tv_order_apply_time)
    TextView tv_order_apply_time;
    @BindView(R.id.tv_logistics)
    TextView tv_logistics;
    @BindView(R.id.tv_cancel)
    TextView tv_cancel;
    @BindView(R.id.tv_payment)
    TextView tv_payment;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_closing_time)
    TextView tv_closing_time;
    @BindView(R.id.tv_delivery_time)
    TextView tv_delivery_time;
    @BindView(R.id.rl_tab_btn)
    RelativeLayout rl_tab_btn;
    @BindView(R.id.ll_logistics)
    LinearLayout ll_logistics;
    @BindView(R.id.tv_freight)
    TextView tv_freight;
    private OrderDetailM.DataBean data;
    private OrderDetailsShopAdapter adapter;
    private OrderDetailModel detailModel;
    private String order_id = "";
    private OrderPayModel orderPayModel;
    private DeleteOrderModel deleteOrderModel;
    private CancelOrderModel cancelOrderModel;
    private ConfirmOrderModel confirmOrderModel;
    private OrderRefundAllModel refundAllModel;
    private static final int SDK_PAY_FLAG = 1;
    private int pay_type = 1;
    private IWXAPI api;
    private List<MyOrdersM.DataBean.ModelsBean.OrderInfoBean> orderInfo = new ArrayList<>();
    private List<OrderDetailM.DataBean.OrderInfoBean> list = new ArrayList<>();
    private int status = 0;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.app.refresh.evaluate")) {
                detailModel.requestOrderDetail(order_id);
            }
        }
    };

    private Handler MyHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        detailModel.requestOrderDetail(order_id);
                        sendBroadcast("action.app.refresh.evaluate");
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details, "交易详情", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constants.APP_ID);
        registerReceiver(receiver, "action.app.refresh.evaluate");
        order_id = getIntent().getStringExtra("order_id");
        orderInfo = (List<MyOrdersM.DataBean.ModelsBean.OrderInfoBean>) getIntent().getSerializableExtra("item");
        if (orderInfo == null) {
            orderInfo = new ArrayList<>();
        }
        detailModel = new OrderDetailPresenter(this, mContext);
        MyLayoutManager manager = new MyLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0.5F), getResources().getColor(R.color.line_color)));
        recyclerView.setLayoutManager(manager);
        adapter = new OrderDetailsShopAdapter(this, onReturnGoods);
        recyclerView.setAdapter(adapter);
        detailModel.requestOrderDetail(order_id);
    }

    /**
     * 申请退换货
     */
    public OrderDetailsShopAdapter.OnReturnGoods onReturnGoods = new OrderDetailsShopAdapter.OnReturnGoods() {
        @Override
        public void onReturnShop(OrderDetailM.DataBean.OrderInfoBean infoBean, OrderDetailM.DataBean orderDetailM) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("serializable", infoBean);
            bundle.putInt("status", status);// 订单状态
            bundle.putInt("goods_num", infoBean.getNum());// 订单总数量
            bundle.putString("order_sn", orderDetailM.getOrder_sn());
            bundle.putString("shop_name", orderDetailM.getShop_name());
            bundle.putString("real_price", infoBean.getReal_price());
            bundle.putString("shop_price", orderDetailM.getShop_price());

            bundle.putString(Constant.EXTRA_USER_ID, orderDetailM.getShop_hx());
            bundle.putString(Constant.EXTRA_NICK_ID, orderDetailM.getShop_name());
            intent.setClass(mContext, ReturnGoodsActivity.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, 300);
        }
    };

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void orderDetailSuccess(OrderDetailM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                data = model.getData();
                list = data.getOrderInfo();
                status = data.getStatus();
                adapter.setShopName(data.getShop_name());
                adapter.setList(list);
                adapter.setOrderDetailM(data);
                adapter.setStatus(status);
                adapter.notifyDataSetChanged();

                String address_member = data.getAddress_member();
                String address_mobile = data.getAddress_mobile();
                String address_str = data.getAddress_str();
                String note = data.getNote();
                String order_sn = data.getOrder_sn();
                int comment_status = data.getComment_status();// 是否评论 0未 1已
                if (!Tools.isNull(address_mobile)) {
                    tv_name.setText("收货人：" + address_member + "   " + address_mobile);
                    tv_address.setText("收货地址：" + address_str);
                }
//                else {
//                    tv_name.setText("收货人：" + data.getWarehouse_member() + "   " + data.getWarehouse_mobile());
//                    tv_address.setText("收货地址：" + data.getWarehouse_str());
//                }

                tv_freight.setText("￥" + data.getPost_price());
                if (!Tools.isNull(note)) {
                    tv_note.setText("留言备注：" + note);
                } else {
                    tv_note.setText("留言备注：无");
                }
                tv_order_num.setText("订单编号：" + order_sn);
                int updated_at = data.getUpdated_at();
                int created_at = data.getCreated_at();
                tv_order_time.setText("创建时间：" + Tools.SubTime3(created_at + ""));

                tv_money.setText("￥" + data.getPay_price());
                List<OrderDetailM.DataBean.OrderLogBean> order_log = data.getOrder_log();
                switch (status) {
                    case 0:
                        //待付款
                        // 待付款 显示去支付、取消订单
                        tv_cancel.setVisibility(View.VISIBLE);
                        tv_cancel.setText("取消订单");
                        tv_logistics.setVisibility(View.GONE);
                        tv_payment.setVisibility(View.VISIBLE);
                        tv_payment.setText("去付款");
                        tv_payment.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_true));
                        Tools.modifyTextViewDrawable(mContext, tv_status, R.mipmap.nopay_1x, 0);
                        tv_delivery_time.setVisibility(View.GONE);
                        tv_closing_time.setVisibility(View.GONE);
                        tv_order_apply_time.setVisibility(View.GONE);
                        setStatus(order_log);
                        tv_status.setText("等待付款...");
                        tv_closing_time.setVisibility(View.GONE);
                        tv_delivery_time.setVisibility(View.GONE);
                        rl_tab_btn.setVisibility(View.VISIBLE);
                        ll_logistics.setVisibility(View.GONE);
                        break;
                    case 1:
                        // 已支付
                        Tools.modifyTextViewDrawable(mContext, tv_status, R.mipmap.daifahuo_1x, 0);
                        tv_status.setText("已付款，请耐心等待卖家发货...");
                        tv_delivery_time.setVisibility(View.GONE);
                        tv_closing_time.setVisibility(View.GONE);
                        tv_order_time.setVisibility(View.VISIBLE);
                        tv_payment.setVisibility(View.VISIBLE);
                        tv_order_apply_time.setVisibility(View.VISIBLE);
                        //已支付 没有可操作的
                        tv_logistics.setVisibility(View.INVISIBLE);
                        tv_cancel.setVisibility(View.INVISIBLE);
                        tv_payment.setText("全额退款");
                        rl_tab_btn.setVisibility(View.VISIBLE);
                        ll_logistics.setVisibility(View.GONE);
                        setStatus(order_log);
                        break;
                    case 2:
                        //已发货
                        tv_cancel.setVisibility(View.GONE);
                        tv_cancel.setText("");
                        tv_logistics.setVisibility(View.VISIBLE);
                        tv_logistics.setText("查看物流");
                        tv_payment.setVisibility(View.VISIBLE);
                        tv_payment.setText("确认收货");
                        tv_payment.setTextColor(ContextCompat.getColor(mContext, R.color.color_53));
                        Tools.modifyTextViewDrawable(mContext, tv_status, R.mipmap.yifahuo_1x, 0);
                        tv_status.setText("卖家已发货");
                        tv_closing_time.setVisibility(View.GONE);
                        setStatus(order_log);
                        rl_tab_btn.setVisibility(View.VISIBLE);
                        ll_logistics.setVisibility(View.VISIBLE);
                        break;
                    case 3:
                        // 已收货
                        tv_cancel.setVisibility(View.VISIBLE);
                        tv_logistics.setVisibility(View.GONE);
                        ll_logistics.setVisibility(View.VISIBLE);
                        tv_cancel.setText("删除订单");
                        tv_logistics.setText("");
                        tv_payment.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_true));
                        Tools.modifyTextViewDrawable(mContext, tv_status, R.mipmap.wancheng_1x, 0);
                        tv_status.setText("交易成功");
                        setStatus(order_log);
                        if (comment_status == 0) {
                            tv_payment.setText("去评价");
                            tv_payment.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_true));
                            tv_payment.setVisibility(View.VISIBLE);
                        } else {
                            tv_payment.setVisibility(View.GONE);
                        }
                        rl_tab_btn.setVisibility(View.VISIBLE);
                        break;
                    case 4:
                        // 交易成功
                        tv_cancel.setVisibility(View.VISIBLE);
                        tv_logistics.setVisibility(View.GONE);
                        ll_logistics.setVisibility(View.VISIBLE);
                        switch (comment_status) {
                            case 0:
                                tv_payment.setVisibility(View.VISIBLE);
                                tv_payment.setText("去评价");
                                break;
                            case 1:
                                tv_payment.setVisibility(View.GONE);
                                tv_payment.setText("");
                                break;
                        }
                        tv_cancel.setText("删除订单");
                        tv_logistics.setText("");
                        tv_payment.setTextColor(ContextCompat.getColor(mContext, R.color.tab_color_true));
                        Tools.modifyTextViewDrawable(mContext, tv_status, R.mipmap.sel01_sel_1x, 0);
                        tv_status.setText("交易成功");
                        setStatus(order_log);
                        rl_tab_btn.setVisibility(View.VISIBLE);
                        break;
                    case 17:
                        // 已关闭
                        tv_status.setText("该订单已被取消..");
                        tv_cancel.setVisibility(View.INVISIBLE);
                        tv_logistics.setVisibility(View.INVISIBLE);
                        tv_payment.setVisibility(View.VISIBLE);
                        tv_payment.setText("删除订单");
                        ll_logistics.setVisibility(View.GONE);
                        tv_payment.setTextColor(ContextCompat.getColor(mContext, R.color.color_53));
                        rl_tab_btn.setVisibility(View.VISIBLE);
                        setStatus(order_log);
                        break;
                    default:
                        Tools.modifyTextViewDrawable(mContext, tv_status, R.mipmap.sel01_sel_1x, 0);
                        tv_status.setText("交易成功");
                        rl_tab_btn.setVisibility(View.GONE);
                        ll_logistics.setVisibility(View.GONE);
                        setStatus(order_log);
                        break;

                }

            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    /**
     * 根据订单状态 显示
     *
     * @param order_log
     */
    public void setStatus(List<OrderDetailM.DataBean.OrderLogBean> order_log) {
        String order_status_title = "";
        if (order_log.size() > 0) {
            tv_order_time.setVisibility(View.VISIBLE);
            order_status_title = order_log.get(0).getOrder_status_title();
            tv_order_time.setText(order_status_title + "：" + Tools.SubTime3(order_log.get(0).getCreated_at()));
        } else {
            tv_order_time.setVisibility(View.GONE);
        }
        if (order_log.size() > 1) {
            tv_order_apply_time.setVisibility(View.VISIBLE);
            order_status_title = order_log.get(1).getOrder_status_title();
            tv_order_apply_time.setText(order_status_title + "：" + Tools.SubTime3(order_log.get(1).getCreated_at()));
        } else {
            tv_order_apply_time.setVisibility(View.GONE);
        }
        if (order_log.size() > 2) {
            order_status_title = order_log.get(2).getOrder_status_title();
            tv_delivery_time.setVisibility(View.VISIBLE);
            tv_delivery_time.setText(order_status_title + "：" + Tools.SubTime3(order_log.get(2).getCreated_at()));
        } else {
            tv_delivery_time.setVisibility(View.GONE);
        }
        if (order_log.size() > 3) {
            order_status_title = order_log.get(3).getOrder_status_title();
            tv_closing_time.setVisibility(View.VISIBLE);
            tv_closing_time.setText(order_status_title + "：" + Tools.SubTime3(order_log.get(3).getCreated_at()));
        } else {
            tv_closing_time.setVisibility(View.GONE);
        }
    }

    @Override
    public void cancelOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void confirmOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void deleteOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {
    }

    @Override
    public void orderRefundAllSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                detailModel.requestOrderDetail(order_id);
                T.showToast(mContext, model.getMsg());
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    @OnClick({R.id.tv_cancel, R.id.tv_logistics, R.id.tv_payment, R.id.ll_logistics})
    public void onClick(View view) {
        String text = "";
        switch (view.getId()) {
            case R.id.tv_cancel:
                text = ((TextView) view).getText().toString().trim();
                if (text.equals("删除订单")) {
                    // 删除订单
                    showOrderDialog(1, order_id + "");
                    deleteOrderModel = new DeleteOrderPresenter(OrderDetailsActivity.this, mContext);
                } else if (text.equals("取消订单")) {
                    showOrderDialog(2, order_id + "");
                    cancelOrderModel = new CancelOrderPresenter(OrderDetailsActivity.this, mContext);
                }
                break;
            case R.id.tv_logistics:
                text = ((TextView) view).getText().toString().trim();
                if (text.equals("查看物流")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("postid", data.getPost_sn());
                    bundle.putString("use_ydx", data.getUse_ydx());
                    Log.v("vin",data.getPost_name()+"!!!!!2222!!!"+data.getUse_ydx());
                    Tools.copy(data.getPost_sn(), OrderDetailsActivity.this);
                    startAct(LogisticsActivity.class, bundle);
                }
                break;
            case R.id.tv_payment:
                text = ((TextView) view).getText().toString().trim();
                if (text.equals("删除订单")) {
                    showOrderDialog(1, order_id + "");
                    deleteOrderModel = new DeleteOrderPresenter(OrderDetailsActivity.this, mContext);
                } else if (text.equals("确认收货")) {
                    // 确认收货
                    showOrderDialog(3, order_id + "");
                    confirmOrderModel = new ConfirmOrderPresenter(OrderDetailsActivity.this, mContext);
                } else if (text.equals("去评价")) {
                    Bundle bundle = new Bundle();
                    bundle.putString("order_id", data.getOrder_id() + "");
                    bundle.putString("shop_name", data.getShop_name() + "");
                    bundle.putString("shop_avatar", data.getShop_avatar());
                    bundle.putSerializable("orderInfo", (Serializable) orderInfo);
                    startAct(CommentActivity.class, bundle);
                } else if (text.equals("去付款")) {
                    // 去付款
                    pay_type = data.getPay_type();
                    showApplyDialog(data.getOrder_id() + "");
                } else if (text.equals("全额退款")) {
                    refundAllModel = new OrderRefundAllPresenter(this, mContext);
                    showOrderDialog(4, order_id + "");
                }
                break;
            case R.id.ll_logistics:
                Bundle bundle = new Bundle();
                bundle.putString("postid", data.getPost_sn());
                bundle.putString("use_ydx", data.getUse_ydx());
                Tools.copy(data.getPost_sn(), OrderDetailsActivity.this);
                startAct(LogisticsActivity.class, bundle);
                break;
        }
    }


    /**
     * 支付方式
     */
    protected void showApplyDialog(final String order_id) {
        final CustomDialog dialog = new CustomDialog(mContext, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, R.layout.wind_apply_dialog_xml, R.style.Theme_dialog);
        ImageView iv_alipy = (ImageView) dialog.findViewById(R.id.iv_alipy);
        ImageView iv_wechat = (ImageView) dialog.findViewById(R.id.iv_wechat);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        orderPayModel = new OrderPayPresenter(OrderDetailsActivity.this, mContext);
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        iv_alipy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_type = 1;
                orderPayModel.requestOrderPay(order_id, pay_type + "");
                dialog.dismiss();
            }
        });
        iv_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_type = 2;
                orderPayModel.requestOrderPay(order_id, pay_type + "");
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    /**
     * 操作订单
     */
    private void showOrderDialog(final int type, final String orderId) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        final TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        switch (type) {
            case 1:
                tv_content.setText("确定要删除该订单吗？");
                break;
            case 2:
                tv_content.setText("确定要取消该订单吗？");
                break;
            case 3:
                tv_content.setText("请先确认订单无误，在收货。");
                break;
            case 4:
                tv_content.setText("确定要申请全额退款吗？");
                break;
        }

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog(getString(R.string.app_loading));
                switch (type) {
                    case 1:
                        deleteOrderModel.requestDeleteOrder(0, orderId);
                        break;
                    case 2:
                        cancelOrderModel.requestCancelOrder(orderId);
                        break;
                    case 3:
                        confirmOrderModel.requestConfirmOrder(orderId);
                        break;
                    case 4:
                        refundAllModel.orderRefundAll(orderId);
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void orderPaySuccess(OrderM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                OrderM.DataBean bean = model.getData();
                String params = bean.getParams();
                switch (pay_type) {
                    case 1:
                        new AlipayUtil(OrderDetailsActivity.this, params, MyHandler);
                        break;
                    case 2:
                        wechatApply(bean);
                        break;
                }
            }
        }

    }


    /**
     * 微信支付
     *
     * @param bean
     */

    private void wechatApply(OrderM.DataBean bean) {
        try {
            PayReq req = new PayReq();
            req.appId = bean.getAppid();
            req.partnerId = bean.getPartnerid();
            req.prepayId = bean.getPrepayid();
            req.nonceStr = bean.getNoncestr();
            req.timeStamp = bean.getTimestamp() + "";
            req.packageValue = bean.getPackageX();
            req.sign = bean.getSign();
            Toast.makeText(this, "正在发起微信支付，请稍候...", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.registerApp(Constants.APP_ID);
            api.sendReq(req);
        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
        }
    }
}
